package com.qinhao.loveCrowdFunding.config;

import com.qinhao.loveCrowdFunding.handler.MyMessageHandler;
import com.qinhao.loveCrowdFunding.utils.AdminLoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;
    @Autowired
    MyMessageHandler myMessageHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
             .anyRequest().permitAll()
             .and()
             .formLogin()
             .successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req,
                                                HttpServletResponse resp,
                                                Authentication auth)
                    throws IOException, ServletException {
                AdminLoginUtil.getHashSet().add(req.getParameter("username"));
                // 我们可以跳转到指定页面
                resp.sendRedirect("http://localhost:5000/#/reviewOfCrowdfundingInformation");
            }
        })
             .and()
             .csrf().disable();
    }

}
